#!/usr/bin/python
import subprocess
import sys
import re
import os
import shutil
import signal
import optparse
from datetime import datetime

def main():
	
	programs = ["neroAacEnc","ffmpeg", "aften", "MP4Box", "mkvextract", "x264"]
	needed = list()
	for program in programs:
		if not which(program):
			needed.append(program)
	if len(needed) > 0:
		raise Exception("You do not have " + " ".join(needed))
	dca = False
	if which("dcadec"):
		dca = True
		

	(opts, args) = parse_options()	
	input_file = None
	output_file = None
	fps = None
	if opts.input_file:
		input_file = os.path.abspath(opts.input_file)
		if not os.path.isfile(input_file):
			raise Exception(str(opts.input_file) + " does not exist")
	else:
		raise Exception("You have not specified an input file")
	(input_filename, input_ext)  = os.path.splitext(os.path.basename(input_file))
	logfile = os.path.join(os.path.dirname(input_file), "log-" + str(datetime.today().isoformat()) + ".txt")
	fd = open(logfile, 'a')
	fd.write('Start:\n')
	fd.close()
		 
	if opts.output_file:
		output_file = os.path.abspath(opts.output_file)
	else:
		output_file = os.path.join(
		os.path.dirname(input_file), 
		input_filename + ".m4v"
		)
	if opts.fps:
		fps = opts.fps.strip()
		fps_re = re.search('[\d\.]+', fps)
		if not fps_re:
			raise Exception ("You must specify a number for the fps")

	test(output_file)
	input_re = re.sub('\s+', '', input_filename)
	mkm = MKV2MP4(input_file, dest=output_file, tmp=os.path.join('/tmp', input_re), fps=fps, dca=dca, log=logfile)
	converted_file_path = mkm.start()
	try:	
		os.remove(logfile)	
	except Exception:
		pass
	print " [o] All Done!"	


def which(program):
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return True
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return True

    return False

def test(path):
	if os.path.isfile(path) or os.path.isdir(path):
		print " [-] The file " + os.path.basename(path) + " already exists"
		while True:
			input = raw_input("\t Would you like to overwrite[y/n]: ")
			if str(input).strip().lower() == "y":
				if os.path.isdir(path):
					try:
						os.rmdir(path)
						break
					except Exception:
						print " [-] " + os.path.basename(path) + " is a non-empty directory"
						while True:
							del input
							input = raw_input("\t Woud you like to recursively delete[y/n]: ")
							if str(input).strip().lower() == "y":
								try:
									shutil.rmtree(path)
									break
								except Exception:
									raise Exception("Could not delete directory contents")
							elif str(input).strip().lower() == "n":
								raise SystemExit
				else:
					try:
						os.remove(path)
						break
					except Exception:
						raise Exception("Could not delete " + os.path.basename(path))
			elif str(input).strip().lower() == "n":
				raise SystemExit
	return





class MKV2MP4:
	import subprocess
	import os
	import re
	def __init__(self, source, dest=None, fps=None, tmp="/tmp", audio=None, log=os.devnull, dca=False):
		"""Setup Log File"""
		
		self.dca = dca
		if log == os.devnull:
			self.log = log
		elif log == None:
			self.log = os.devnull
		else:
			if os.path.isfile(os.path.abspath(log)):
				self.log = log
			else:
				self.log = os.devnull

		if os.path.isfile(source.strip()):
			self.source = source.strip()
		else:
			raise IOError('No such file ' + source)
		(sourcepath, sourcefile) = os.path.split(self.source)
		if dest:
			if os.path.isdir(os.path.dirname(dest)):
				if os.path.exists(dest):
					raise IOError(dest + ' already exists')
				else:
					self.dest = dest.strip()
			else:
				raise IOError(os.path.dirname(dest) + ' does not exist')
		else:
			dest = os.path.join(sourcepath, os.path.splitext(sourcefile)[0] + ".m4v")
			if os.path.exists(dest):
				raise IOError(dest + ' already exists')
			else:
				self.dest = dest
		self.get_info()
		if audio:
			try:
				audio = int(audio)
				self.aacid = audio
				self.ac3id = audio
			except Exception:
				pass

		if fps:
			self.fps = fps.strip()
		if not self.fps:
			raise Exception("Could not find fps: Please specify with -r or --fps")

		self.process_frames()

		self.crop = None

		if os.path.isdir(os.path.abspath(tmp)):
			self.tmp = os.path.abspath(tmp)
		else:
			os.makedirs(os.path.abspath(tmp))
			self.tmp = os.path.abspath(tmp)
		self.tmpfile = os.path.join(self.tmp, os.path.splitext(os.path.basename(self.dest))[0])	
		self.multichannel = False
		self.delete = list()
		self.chap = None
		self.has_chapters = False

	def start(self):
		tracks = list()
		self.cropdetect()
		if self.multichannel:
			tracks.insert(1, self.convert_audio_ac3())
		tracks.insert(2, self.convert_audio_aac())
		tracks.insert(0, self.convert_video())
		if self.has_chapters:
			self.chap = self.get_chapters()
		self.mux(tracks)
		for path in self.delete:
			try:
				os.remove(path)
			except Exception:
				pass
		try:
			shutil.rmtree(self.tmp)
		except Exception:
			pass
		return self.dest

	def get_info(self):
		cmd = ['ffmpeg', '-i', self.source]
		fd = open(self.log, 'a')
		all_data = list()
		info = None
		try:
			info = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			while True:
				data = info.stderr.readline() 
				if len(data) < 1:
					if info.poll() is not None:
						break
				else:
					fd.write(data)
					all_data.append(data)
		except:
			raise
		finally:
			fd.close()
			try:
				info.kill()
			except Exception:
				pass
		videostreams = list()
		audiostreams = list()
		streams = re.findall('stream #0\.[0-9]+.*?$', "".join(all_data), re.M|re.S|re.I)
		duration_re = re.search('.*?duration:\s*?([\d:\.]+),.*', "".join(all_data), re.M|re.I)
		chap_info = re.findall('^\W*chapter.*$', "".join(all_data), re.I|re.M)

		if len(chap_info) > 1:
			self.has_chapters = True

		if duration_re:
			self.process_duration(duration_re.group(1))
		else:
			raise Exception("Could not get time information")
		try:
			for stream in streams:
				stream_sects = stream.strip().split('\n')
				if len(stream_sects) < 1:
					continue
				elif 'video' in stream_sects[0].strip().lower():
					videostreams.append(stream)
				elif 'audio' in stream_sects[0].strip().lower():
					audiostreams.append(stream)
				else:
					continue
		except Exception:
			raise Exception('Could not properly get video info')
		self.get_audio_info(audiostreams)
		self.get_video_info(videostreams[0])

	def process_frames(self):
		try:
			if self.duration is None or self.fps is None:
				raise Exception("No time information found")

			self.frames = int(round(float(self.duration)*float(self.fps)))
		except Exception:
			raise Exception("Could not process frame information")
			
	def process_duration(self, dur):
		try:
			sects = dur.strip().split(":")
			hours = float(sects[0]) * 60 * 60
			minutes = float(sects[1]) * 60
			seconds = float(sects[2])
			total = hours + minutes + seconds
			self.duration = int(round(total))
		except Exception:
			raise Exception('Could not process time information')
				
	def get_audio_info(self, audio_streams):
		multichannel = list()
		twochannel = list()
		for stream in audio_streams:
			info_re = re.compile('.*?stream #\d+\.(?P<id>\d+).*?audio.*?:\s+?(?P<codec>\w+),[a-z0-9\s]+?,\s+?(?P<channels>[\w\.\s]+),.*?', re.I)
			info_match = info_re.search(stream)
			if not info_match:
				continue
			d = info_match.groupdict()	
			new_d = dict()
			for k, v in d.iteritems():
				new_d[k] = v.strip().lower()
			d = new_d
			if d['channels'] == 'stereo':
				d['channels'] = '2'
			else:
				channel_re = re.search('.*?([\d\.]+).*?', d['channels'])
				if channel_re:
					d['channels'] = channel_re.group(1)
				else:
					raise Exception('Could not get audio information')
					
			if divmod(float(d['channels'].strip()), 1)[1] >0:
				d['channels'] = str(divmod(float(self.channels.strip()), 1)[0] + 1)

			if float(d['channels']) > 2:
				multichannel.append(d)
				self.multichannel = True
			else:
				twochannel.append(d)
		if len(twochannel) < 1 and len(multichannel) < 1:
			raise Exception('No good audio tracks found')

		aacstream = self.pick_audio_track(twochannel)
		self.aacid = aacstream['id']
		self.channels = aacstream['channels']
		if len(multichannel) > 0:
			ac3stream = self.pick_audio_track(multichannel)	
			self.ac3id = ac3stream['id']	
			self.ac3channels = ac3stream['channels']
		else:
			self.ac3id = aacstream['id']

	def pick_audio_track(self, tracks):
		tracks_ordered = list()
		for track in tracks:			
			if track['codec'] != 'dca':
				tracks_ordered.append(track)	
		return tracks_ordered[0]		
			


	def get_video_info(self, info):			
		#info_re = re.compile(""".*?duration.*?(?P<duration>\d+).*?width.*?(?P<width>\d+).*?height.*?(?P<height>\d+).*?frame rate.*?(?P<fps>[\d\.]+).*?frame count.*?(?P<frames>\d+).*?""", re.M|re.S|re.I)
		info_re = re.compile('.*?(?P<fps>[\d\.]+) fps.*')	
		
		info_match = info_re.match(info)
		if not info_match:
			self.fps = None
			return
		d = info_match.groupdict()
		
		try:	
			if d['fps'].strip() == '23.98':
				self.fps = '23.976'
			else:
				self.fps = d['fps'].strip()
		except Exception:
			self.fps = None
	 
	def get_chapters(self):
		cmd = ['mkvextract', 'chapters', '-s', self.source]
		fd = open(self.log, 'a')
		output = open(self.tmpfile + '.txt', 'w')
		sys.stdout.write(' [+] Extracting chapter information...')
		sys.stdout.flush()
		ex = None
		try:
			ex = subprocess.Popen(cmd, stdout=output, stderr=fd) 
			s = Spinny()
			while ex.poll() is None:
				s.p()
			fd.close()
			output.close()
			s.exit('success')
			del s
		except SystemExit:
			try:
				ex.kill()
			except Exception:
				pass
			raise SystemExit
		if ex.poll() > 0:
			raise Exception('mkvextract crashed')
		chapterfile = self.tmpfile + '.txt'
		if not os.path.isfile(chapterfile):
			raise Exception(chapterfile + ' does not exist')
		self.delete.append(chapterfile)
		return chapterfile

	def mux(self, tracks):
		cmd = ['MP4Box']	
		for track in tracks:
			cmd.extend(['-add', track])
		if self.has_chapters:
			cmd.extend(['-chap', self.chap]) 
		cmd.extend(['-fps', self.fps])
		cmd.extend([self.dest])
		fd = open(self.log, 'a')
		sys.stdout.write(' [+] Muxing audio and video streams...')
		sys.stdout.flush()
		mp4box = None
		try:
			mp4box = subprocess.Popen(cmd, stdout=fd, stderr=fd)
			s = Spinny()
			while mp4box.poll() is None:
				s.p()
			s.exit('success')
			del s
			if mp4box.returncode > 0:
				raise Exception('MP4Box crashed')
		except SystemExit:
			try:
				mp4box.kill()
			except Exception:
				pass
			raise SystemExit
		if not os.path.isfile(self.dest):	
			raise Exception(self.dest + ' does not exist')	

		return self.dest
			

	def convert_audio_ac3(self):
		import fcntl
		import select
		import progressbar
		import time
		sys.stdout.write(' [+] Converting audio to ' + self.channels + ' dolby-digital sound\n')
		sys.stdout.flush()
		fd = open(self.log, 'a')
		aften = None
		ffmpeg = None
		pbar = None
		channels = 0
		try:
			channels = int(float(self.channels.strip()))
		except Exception:
			pass
		maxsize = int((self.duration*768*channels)/8)
		if maxsize > 0:
			pbar = progressbar.ProgressBar(widgets=[progressbar.Bar('>'), progressbar.Percentage(), progressbar.ReverseBar('<'), progressbar.ETA()], maxval=int(maxsize)).start()
		else:
			print " [-] No progress available because no time information was found"
		try:
			cmd = ['ffmpeg', '-i', self.source, '-vn','-map', '0.' + str(self.ac3id), '-ac', self.channels, '-acodec', 'pcm_s16le', '-async', '1', '-f', 'wav', '-']
			fd.write(" ".join(cmd) + "\n")
			ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			fcntl.fcntl(ffmpeg.stderr.fileno(), fcntl.F_SETFL, fcntl.fcntl(ffmpeg.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)	
			cmd = ['aften', '-b', '448', '-', self.tmpfile + '.ac3']
			fd.write(" ".join(cmd) + "\n")
			aften = subprocess.Popen(cmd, stdin=ffmpeg.stdout, stdout=fd, stderr=fd) 
			size_re = re.compile('.*?size=.*?(\d+).*time.*')
			start = 0
			while ffmpeg.poll() is None:
				try:
					readx = select.select([ffmpeg.stderr.fileno()], [], [])[0]
					if readx:
						data = ffmpeg.stderr.read()	
						if data == '':
							continue
						if start < 11:
							start = start + 1
							time.sleep(1)
							continue
						fd.write(data.strip() + "\n")
						size = size_re.search(data)
						if size:
							sizenum = int(size.group(1).strip())
							pbar.update(sizenum)
				except Exception, e:
					pass
				time.sleep(.1)

			return_aften = aften.wait()
			return_ffmpeg = ffmpeg.returncode

			if return_ffmpeg > 0:
				raise Exception('ffmpeg crashed')
			if return_aften >0:
				raise Exception('aften crashed')

		except SystemExit:
			raise SystemExit
		except Exception, e:
			raise e
		finally:
			fd.close()
			try:
				aften.kill()
			except Exception:
				pass
			try:
				ffmpeg.kill()
			except Exception:
				pass
			fd.close()
			try:
				pbar.finish()
			except Exception:
				pass
				

		ac3file = self.tmpfile + '.ac3'

		if not os.path.isfile(ac3file):
			raise Exception(ac3file + ' failed to be created')
		self.delete.append(ac3file)

		return ac3file

	def convert_video(self):
		import fcntl
		import select
		import progressbar
		import time
 		cmd = ['ffmpeg', '-i', self.source, '-an', '-vsync', '0'] 
		vfsetting = list()
		if self.crop:
			vfsetting.append('crop=' + self.crop)
		if int(self.height) > 990:
			new_height = None	
			for h in range(int(self.height)-2, 0, -2):
				tmp = (float(self.width)*float(h))/float(self.height)
				tmp = round(tmp)
				tmp = int(tmp)
				div, mod = divmod(tmp, 2)
				if int(mod) == 0 and h < 990:
					new_height = h
					break
			vfsetting.append('scale=-1:' + str(new_height))
		if len(vfsetting) > 0:
			cmd.extend(['-vf', ",".join(vfsetting)])
		cmd.extend(['-vcodec', 'libx264', '-flags', '+loop', '-cmp', '+chroma', '-partitions', '+parti8x8+parti4x4+partp8x8+partb8x8', '-me_method', 'umh', '-coder', '1', '-subq', '8', '-me_range', '16', '-g', '250', '-keyint_min', '25', '-sc_threshold', '40', '-i_qfactor', '0.71', '-b_strategy', '2', '-qcomp', '0.6', '-qmin', '10', '-qmax', '51', '-qdiff', '4', '-bf', '3', '-refs', '5', '-directpred', '3', '-trellis', '1', '-flags2', '+bpyramid+mixed_refs+wpred+dct8x8+fastpskip', '-wpredp', '2', '-rc_lookahead', '50', '-crf', '22', '-level', '31', '-threads', '0', '-f', 'h264','-threads', '0','-y', self.tmpfile + '.264'])
		fd = open(self.log, 'a')
		fd.write(" ".join(cmd) + "\n")
		sys.stdout.write(' [+] Encoding the video from the mkv\n')
		sys.stdout.flush()
		ffmpeg = None
		pbar = progressbar.ProgressBar(widgets=[progressbar.Bar('>'), progressbar.Percentage(), ' Frame ', progressbar.SimpleProgress(), '  ', progressbar.ReverseBar('<'), progressbar.ETA()], maxval=int(self.frames)).start()
		start = 0
		try:
			ffmpeg = subprocess.Popen(cmd,stdout=fd, stderr=subprocess.PIPE, close_fds=True)
			fcntl.fcntl(
			ffmpeg.stderr.fileno(), 
			fcntl.F_SETFL, 
			fcntl.fcntl(ffmpeg.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK
			)	
			frame_re = re.compile('.*?frame=.*?(\d+).*fps.*')
			while ffmpeg.poll() is None:
				try:
					readx = select.select([ffmpeg.stderr.fileno()], [], [])[0]
					if readx:
						data = ffmpeg.stderr.read()	
						if len(data) < 1:
							continue
						if start < 11:
							start = start + 1
							time.sleep(.5)
							continue
						fd.write(data.strip()+"\n")
						frames = frame_re.search(data.strip())
						if frames:
							framenum = int(frames.group(1).strip())
							pbar.update(framenum)
				except Exception, e:
					pass
				time.sleep(.1)
			return_ffmpeg = ffmpeg.returncode	
			if return_ffmpeg > 0:
				raise Exception('ffmpeg crashed')
		except SystemExit:
			raise SystemExit
		except Exception, e:
			raise e
		finally:
			try:
				ffmpeg.kill()
			except Exception:
				pass
			try:
				fd.close()
			except Exception:
				pass
			pbar.finish()

		videofile = self.tmpfile + '.264'

		if not os.path.isfile(videofile):
			raise Exception(videofile + ' does not exist')

		self.delete.append(videofile)	
		return videofile

		
	def convert_audio_aac(self):
		import fcntl
		import select
		import progressbar
		import time
		cmd = ['ffmpeg', '-i', self.source, '-vn','-map', '0.' + str(self.aacid), '-ac', '2', '-acodec', 'pcm_s16le', '-async', '1', '-f', 'wav', '-']
		fd = open(self.log, 'a')	
		fd.write(" ".join(cmd) + "\n")
		ffmpeg = None
		nero = None
		mp4box = None
		sys.stdout.write(' [+] Converting audio to low-complexity AAC\n')	
		sys.stdout.flush()
		pbar = None
		channels = 2
		maxsize = int((self.duration*768*channels)/8)
		if maxsize > 0:
			pbar = progressbar.ProgressBar(widgets=[progressbar.Bar('>'), progressbar.Percentage(), progressbar.ReverseBar('<'), progressbar.ETA()], maxval=maxsize).start()
		else:
			print " [-] No progress available because no time information was found"
		try:
			ffmpeg = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			cmd = ['neroAacEnc', '-ignorelength', '-lc', '-q', '0.6', '-if', '-', '-of', self.tmpfile + '.m4a']	
			fd.write(" ".join(cmd) + "\n")
			fcntl.fcntl(ffmpeg.stderr.fileno(), fcntl.F_SETFL, fcntl.fcntl(ffmpeg.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)	
			nero = subprocess.Popen(cmd, stdin=ffmpeg.stdout, stdout=fd, stderr=fd
			)
			start = 0
			size_re = re.compile('.*?size=.*?(\d+).*time.*')
			while ffmpeg.poll() is None:
				try:
					readx = select.select([ffmpeg.stderr.fileno()], [], [])[0]
					if readx:
						data = ffmpeg.stderr.read()	
						if data == '':
							continue
						if start < 11:
							start = start + 1
							time.sleep(.1)
							continue
						fd.write(data.strip() + "\n")
						size = size_re.search(data)
						if size:
							sizenum = int(size.group(1).strip())
							pbar.update(sizenum)
				except Exception, e:
					pass
				time.sleep(.1)
			
			return_nero = nero.wait()
			return_ffmpeg = ffmpeg.returncode

			if return_ffmpeg > 0: 
				raise Exception('ffmpeg crashed decoding ' + self.source)
			if return_nero > 0:
				raise Exception('neroAacEnc crashed encoding ' + self.source)
		except SystemExit:
			raise SystemExit
		except Exception, e:
			raise e
		finally:
			fd.close()
			try:
				ffmpeg.kill()
			except Exception:
				pass
			try:
				nero.kill()
			except Exception:
				pass
			fd.close()
			try:
				pbar.finish()
			except Exception:
				pass

		fd = open(self.log, 'a')	
		s = Spinny()
		try:
		
			sys.stdout.write(' [+] Extracting AAC from M4A container...')
			sys.stdout.flush()
			cmd = ['MP4Box', '-raw', '1', self.tmpfile + '.m4a'] 
			fd.write(" ".join(cmd) + "\n")
			mp4box = subprocess.Popen(cmd, stdout=fd, stderr=fd)
			while mp4box.poll() is None:
				s.p()
			return_mp4box = mp4box.returncode 
			if return_mp4box > 0:
				raise Exception('MP4Box crashed')
			s.exit('success')	
		except SystemExit:
			s.exit('failed')	
			raise SystemExit
		except Exception, e:
			s.exit('failed')	
			raise e
		finally:
			fd.close()
			try:
				mp4box.kill()
			except Exception:
				pass
			fd.close()

		if not os.path.isfile(self.tmpfile + "_track1.aac"):
			raise Exception('MP4Box failed')	

		os.rename(self.tmpfile + "_track1.aac", self.tmpfile + ".aac")
		aacfile = self.tmpfile + '.aac'
		try:
			os.remove(self.tmpfile + ".m4a")
		except Exception:
			pass
		self.delete.append(aacfile)
		return aacfile
		
		

	def cropdetect(self):
		total_loops = 10
		crop = list()
		sys.stdout.write(' [+] Finding crop settings...')
		sys.stdout.flush()
		s = Spinny()
		for x in range(1, total_loops):
			skip = x * 35
			cmd = ['ffmpeg', '-ss', str(skip), '-vframes', '10', '-i', self.source, '-vf', 'cropdetect=20:16', '-sn', '-an', '-f', 'mp4', '-y', os.devnull]
			p = None
			try:
				p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
				
				while p.poll() is None:
					s.p()
				return_code = p.poll()
				if return_code > 0:
					raise Exception('ffmpeg crashed')
				for line in p.stderr.readlines():
					crop_re = re.search('.*crop=(.*)$', line)
					if crop_re:
						crop.append(crop_re.group(1).strip())
						break
			except SystemExit:
				try:
					s.exit('failed')
					p.kill()
				except Exception:
					pass
				raise SystemExit
			except Exception, e:
				try:
					s.exit('failed')
					p.kill()
				except Exception:
					pass
				raise e
				

		s.exit('success')
		del s
		final_crop = None
		gw = 0
		gh = 0
		for x in crop:
			try:
				sects = x.split(":")
				width = int(sects[0])
				height = int(sects[1])
				if width > gw or height > gh:
					gw = width
					gh = height
					final_crop = x
			except Exception:
				continue
			
		self.crop = final_crop.strip() 
		self.height = gh
		self.width = gw

class Spinny:
	import time
	def __init__(self):
		self.bspace = 0
		self.current = 0
		self.spin = ['/', '-', '\\', '|']

	def p(self):
		import time
		for x in range(0, self.bspace):
			self.echo('\b')
			self.bspace = self.bspace -1

		self.echo(self.spin[self.current])		
		current = self.current + 1	
		self.bspace = self.bspace+1
		if current > 3:
			self.current = 0
		else:
			self.current = current
		time.sleep(.25)
		
	def echo(self, line):
		sys.stdout.write(line)
		sys.stdout.flush()
	def exit(self, line=''):
		for x in range(0, self.bspace):
			self.echo('\b')
		self.echo(line)
		self.echo('\n')



def signal_handler(sigint, frame):
	raise SystemExit

def exit(num=0):
	print " [-] Exiting..."
	try:
		os.wait()
	except Exception:
		pass

	sys.exit(num)

def parse_options():
	parser = optparse.OptionParser()
	parser.add_option('-o', '--output',  dest='output_file', action='store', type='string')
	parser.add_option('-i', '--input', dest='input_file', action='store', type='string')
	parser.add_option('-r', '--fps', dest='fps', action='store', type='string')
	(opts, args) = parser.parse_args()
	return (opts,args)


if __name__ == "__main__":
	try:
		signal.signal(signal.SIGINT, signal_handler)
		main()
	except Exception, e:
		print " [-] " + str(e)
		exit(1)	
			
	except SystemExit:
		exit(1)
	else:
		exit(1)
	

